package com.suwenhao.controller;


import com.alibaba.fastjson.JSONObject;
import com.suwenhao.entity.User;
import com.suwenhao.service.UserService;
import com.suwenhao.service.WxService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * @Author:suwenhao
 * @Description: 测试
 * @Date: Created in 2020/9/22 17:35
 */

@WebServlet("/wx/*")
public class WxChatServlet extends BaseServlet {

    private WxService wxService = new WxService();
    private UserService userService=new UserService();

    protected void wx_login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Properties pro = new Properties();
        pro.load(WxChatServlet.class.getClassLoader().getResourceAsStream("config.properties"));

        String appId = pro.getProperty("wx.AppID");

        String redirec_Uri = pro.getProperty("wx.redirect_uri");

//        String appId="wx3500b25b23938d73";
//


        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code" +
                "&appid=" + appId +
                "&redirect_uri=" + redirec_Uri +
                "&scope=snsapi_login";

        System.out.println(url);
        resp.sendRedirect(url);
    }

    protected void wxLoginCallBack(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        System.out.println("微信回调了");

        String appId = "wx3500b25b23938d73";

        String secret = "56ee69a0faf098b3ce3c808cc6dac1ff";

        String code = req.getParameter("code");

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appId +
                "&secret=" + secret +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject jsonObj = getUserInfo(url);
//        System.out.println(jsonObj);

        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonObj.getString("access_token") +
                "&openid=" + jsonObj.getString("openid");
        JSONObject jsonObject = getUserInfo(url);
        System.out.println(jsonObject);

        // 根据微信的openid查询此用户原来有没有使用过微信登录
        User user = wxService.weChatAccount(jsonObj.getString("openid"));

        if (user == null) {
            user = new User();
            // 用户的头像
            user.setPic(jsonObject.getString("headimgurl"));
            //性别
            user.setSex(jsonObject.getString("sex"));
            // 用户的真实姓名
            user.setRealName(jsonObject.getString("nickname"));
            //用户名

            // 注册一个新的用户
            userService.add(user);

        }

        HttpSession session = req.getSession();

//        session.setAttribute();

    }

    private JSONObject getUserInfo(String url) {

        try {
//            创建一个httpClient请求
            CloseableHttpClient client = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(url);

            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String result = EntityUtils.toString(entity, Charset.forName("UTF8"));

                return JSONObject.parseObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
